<template>
  <div class="decoration-wrap">
    <!-- 顶部：申请 + 搜索 -->
    <div class="tool-bar" style="display: flex; align-items: center; margin-bottom: 16px; padding: 8px 0;">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="openAddDialog">
        装修申请
      </el-button>
      <el-form :inline="true" size="small" style="margin-left: auto; display: flex; align-items: center;">
        <el-form-item style="margin-bottom: 0; margin-right: 8px;">
          <el-input
            v-model="keyword"
            placeholder="请输入姓名/房号/手机号"
            clearable
            style="width: 260px"
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0;">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      size="small"
      style="width: 100%; margin-bottom: 16px;"
      header-cell-class-name="table-head"
      v-loading="loading"
    >
      <el-table-column label="小区" prop="communityName" min-width="100" />
      <el-table-column label="楼栋/单元/房号" width="180">
        <template #default="{ row }">
          {{ row.buildingName || '' }} {{ row.unitName || '' }} {{ row.roomName || '' }}
        </template>
      </el-table-column>
      <el-table-column label="装修公司" prop="constructionCompany"  min-width="100" />
      <el-table-column label="申请人" prop="renovationApplyPerson"  min-width="100" />
      <el-table-column label="申请时间" width="160">
        <template #default="{ row }">
          {{ formatTime(row.renovationApplyTime) }}
        </template>
      </el-table-column>
      <el-table-column label="装修押金(元)" prop="renovationDeposit"  min-width="100" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag 
            :type="row.renovationStatus === 0 ? 'info' : 'success'" 
            size="mini"
          >
            {{ row.renovationStatus === 0 ? '待验收' : '已完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="装修内容"  min-width="100">
        <template #default="{ row }">{{ row.renovationContent || row.renovationDesc || '--' }}</template>
      </el-table-column>
      <el-table-column label="审批人" prop="renovationApprover" width="120">
        <template #default="{ row }">{{ row.renovationApprover || '--' }}</template>
      </el-table-column>
      <el-table-column label="操作"  min-width="100" fixed="right">
        <template #default="{ row }">
          <!-- 待验收状态才显示验收按钮 -->
          <el-button
            v-if="row.renovationStatus === 0 && !row.complaintAcceptPerson" 
            type="text"
            size="mini"
            @click="openAcceptDialog(row)"
            style="color: #2d8cf0;"
          >验收</el-button>
          <el-button 
            type="text" 
            size="mini" 
            @click="openEditDialog(row)"
            style="color: #19be6b;"
          >编辑</el-button>
          <el-button 
            type="text" 
            size="mini" 
            @click="openDetailDialog(row)"
            style="color: #ff9900;"
          >详情</el-button>
          <el-button 
            type="text" 
            size="mini" 
            @click="handleDelete(row)"
            style="color: #ed4014;"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" style="display: flex; justify-content: flex-end; align-items: center;">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :disabled="total === 0"
      />
    </div>

    <!-- 验收弹窗 -->
    <el-dialog
      title="装修验收"
      :visible.sync="acceptDialogVisible"
      width="400px"
      destroy-on-close
    >
      <el-form :model="acceptForm" :rules="acceptRules" ref="acceptFormRef" label-width="120px">
        <el-form-item label="验收结果" prop="approveResult">
          <el-radio-group v-model="acceptForm.status">
            <el-radio label="通过">通过</el-radio>
            <el-radio label="不通过">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="验收意见" prop="approveRemark">
          <el-input
            type="textarea"
            v-model="acceptForm.acceptanceDesc"
            placeholder="请输入验收意见"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="验收人" prop="approver">
          <el-input
            v-model="acceptForm.renovationAcceptance"
            placeholder="请输入审批人姓名"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="acceptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAccept">提交验收</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗（简化版，可根据实际需求扩展） -->
    <el-dialog
      title="装修申请详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      destroy-on-close
    >
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="小区名称">{{ detailForm.communityName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="房屋信息">
          {{ detailForm.buildingName || '' }} {{ detailForm.unitName || '' }} {{ detailForm.roomName || '' }}
        </el-descriptions-item>
        <el-descriptions-item label="装修公司">{{ detailForm.constructionCompany || '--' }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ detailForm.renovationApplyPerson || '--' }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">
          {{ formatTime(detailForm.renovationApplyTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="装修押金">{{ detailForm.renovationDeposit || 0 }} 元</el-descriptions-item>
        <el-descriptions-item label="装修状态">
          <el-tag :type="detailForm.renovationStatus === 0 ? 'info' : 'success'" size="mini">
            {{ detailForm.renovationStatus === 0 ? '待验收' : '已完成' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审批人">{{ detailForm.renovationApprover || '--' }}</el-descriptions-item>
        <el-descriptions-item label="装修内容" :span="2">
          <el-input
            type="textarea"
            :value="detailForm.renovationContent || detailForm.renovationDesc || '--'"
            rows="4"
            readonly
          />
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

     <div class="decoration-wrap">
    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑装修申请' : '新增装修申请'"
      :visible.sync="addEditDialogVisible"
      width="500px"
      destroy-on-close
    >
      <!-- 新增表单 -->
      <el-form v-if="!isEdit" :model="addEditForm" :rules="addEditRules" ref="addEditFormRef" label-width="120px">
        <el-form-item label="小区名称" prop="communityName">
          <el-input v-model="addEditForm.communityName" placeholder="请输入小区名称" />
        </el-form-item>
        <el-form-item label="楼栋号" prop="buildingName">
          <el-input v-model="addEditForm.buildingName" placeholder="请输入楼栋号" />
        </el-form-item>
        <el-form-item label="单元号" prop="unitName">
          <el-input v-model="addEditForm.unitName" placeholder="请输入单元号" />
        </el-form-item>
        <el-form-item label="房号" prop="roomName">
          <el-input v-model="addEditForm.roomName" placeholder="请输入房号" />
        </el-form-item>
        <el-form-item label="装修公司" prop="constructionCompany">
          <el-input v-model="addEditForm.constructionCompany" placeholder="请输入装修公司" />
        </el-form-item>
        <el-form-item label="申请人" prop="renovationApplyPerson">
          <el-input v-model="addEditForm.renovationApplyPerson" placeholder="请输入申请人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="renovationApplyPhone">
          <el-input v-model="addEditForm.renovationApplyPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="装修押金" prop="renovationDeposit">
          <el-input v-model.number="addEditForm.renovationDeposit" placeholder="请输入装修押金（元）" />
        </el-form-item>
        <el-form-item label="装修内容" prop="renovationContent">
          <el-input
            type="textarea"
            v-model="addEditForm.renovationContent"
            placeholder="请描述装修内容"
            rows="3"
          />
        </el-form-item>
      </el-form>

      <!-- 编辑表单 -->
     <el-form :model="addEditForm" :rules="addEditRules" ref="addEditFormRef" label-width="120px">
        <el-form-item label="装修公司" prop="constructionCompany">
          <el-input v-model="addEditForm.constructionCompany" placeholder="请输入装修公司" />
        </el-form-item>
        <el-form-item label="装修押金" prop="renovationDeposit">
          <el-input v-model.number="addEditForm.renovationDeposit" placeholder="请输入装修押金（元）" />
        </el-form-item>
        <el-form-item label="装修内容" prop="renovationContent">
          <el-input
            type="textarea"
            v-model="addEditForm.renovationContent"
            placeholder="请描述装修内容"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="装修描述" prop="renovationDesc">
          <el-input v-model="addEditForm.renovationDesc" placeholder="请输入装修描述" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddEdit">提交</el-button>
      </div>
    </el-dialog>
  </div>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="删除确认"
      :visible.sync="deleteDialogVisible"
      width="300px"
      destroy-on-close
    >
      <p style="color: #ed4014;">确定要删除这条装修申请记录吗？删除后不可恢复！</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDelete">确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DecorationMgmt',
  data() {
    return {
      // 表格数据
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      keyword: '',
      loading: false,

      // 验收弹窗相关
      acceptDialogVisible: false,
      acceptForm: {
        renovationId: '',          // 装修ID
        status: '',                // 验收结果（"通过" 或 "未通过"）
        renovationAcceptance: '',  // 验收人
        acceptanceDesc: ''         // 验收意见
      },
      acceptRules: {
        
      },

      // 详情弹窗相关
      detailDialogVisible: false,
      detailForm: {},

        // 添加
        addEditDialogVisible: false,
        isEdit: false, // true-编辑，false-新增
        addEditForm: {
          renovationId: '', // 编辑时需要
          communityName: '',
          buildingName: '',
          unitName: '',
          roomName: '',
          constructionCompany: '',
          renovationApplyPerson: '',
          renovationApplyPhone: '',
          renovationDeposit: 0,
          renovationContent: ''
        },
        editForm: {
          renovationId: '',
          constructionCompany: '',
          renovationDeposit: 0,
          renovationContent: '',
          renovationDesc: ''
        },
        addEditRules: {
          communityName: [{ required: true, message: '请输入小区名称', trigger: 'blur' }],
          buildingName: [{ required: true, message: '请输入楼栋号', trigger: 'blur' }],
          unitName: [{ required: true, message: '请输入单元号', trigger: 'blur' }],
          roomName: [{ required: true, message: '请输入房号', trigger: 'blur' }],
          constructionCompany: [{ required: true, message: '请输入装修公司', trigger: 'blur' }],
          renovationApplyPerson: [{ required: true, message: '请输入申请人姓名', trigger: 'blur' }],
          renovationApplyPhone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
          ],
          renovationDeposit: [
            { required: true, message: '请输入装修押金', trigger: 'blur' },
            { type: 'number', min: 0, message: '押金不能为负数', trigger: 'blur' }
          ],
          renovationContent: [{ required: true, message: '请描述装修内容', trigger: 'blur' }]
        },
        // 编辑表单的验证规则
        editRules: {
          constructionCompany: [{ required: true, message: '请输入装修公司', trigger: 'blur' }],
          renovationDeposit: [{ required: true, message: '请输入装修押金', trigger: 'blur' }],
          renovationContent: [{ required: true, message: '请输入装修内容', trigger: 'blur' }],
          renovationDesc: [{ required: true, message: '请输入装修描述', trigger: 'blur' }]
        },

      // 删除弹窗相关
      deleteDialogVisible: false,
      deleteId: '' // 待删除的ID
    }
  },
  mounted() {
    // 初始化表格数据
    this.fetchTable()
  },
  methods: {
   
    formatTime(time) {
      if (!time) return '--'
      // 处理时间戳（若为10位时间戳，转为13位）
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000
      }
      const date = new Date(time)
      // 验证日期有效性
      if (isNaN(date.getTime())) return '--'
      // 补零函数
      const padZero = (num) => num.toString().padStart(2, '0')
      const year = date.getFullYear()
      const month = padZero(date.getMonth() + 1) // 月份0-11，需+1
      const day = padZero(date.getDate())
      const hours = padZero(date.getHours())
      const minutes = padZero(date.getMinutes())
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    /**
     * 获取表格数据（通用：支持普通查询和搜索）
     */
    fetchTable() {
      this.loading = true
      // 区分普通查询和搜索
      if (this.keyword.trim()) {
        // 搜索接口：后端是POST + @RequestParam keyword + @RequestBody PageForm
        this.$axios.post("http://localhost:8080/renovation/renovation/search",
          { page: this.currentPage, size: this.pageSize }, // PageForm参数
          { params: { keyword: this.keyword } } // URL参数（keyword）
        ).then(res => {
          this.handleResponse(res)
        }).catch(err => {
          this.handleError(err, '搜索失败')
        })
      } else {
        // 普通查询（查所有）：POST + @RequestBody PageForm
        this.$axios.post("http://localhost:8080/renovation/list", {
          page: this.currentPage,
          size: this.pageSize
        }).then(res => {
          this.handleResponse(res)
        }).catch(err => {
          this.handleError(err, '获取列表失败')
        })
      }
    },

    /**
     * 处理接口响应（通用）
     */
    handleResponse(res) {
      this.loading = false
      if (res.data.code === 200 && res.data.data) {
        this.tableData = res.data.data.records || []
        this.total = res.data.data.total || 0
      } else {
        this.$message.error(res.data.msg || '接口返回异常')
        this.tableData = []
        this.total = 0
      }
    },

    /**
     * 处理接口错误（通用）
     */
    handleError(err, msg) {
      this.loading = false
      console.error(err)
      this.$message.error(msg || '网络异常，请稍后重试')
      this.tableData = []
      this.total = 0
    },

    /**
     * 分页-页码变更
     */
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchTable()
    },

    /**
     * 分页-页大小变更
     */
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1 // 重置到第一页
      this.fetchTable()
    },

    /**
     * 搜索按钮点击
     */
    handleSearch() {
      this.currentPage = 1 // 搜索重置到第一页
      this.fetchTable()
    },

    /**
     * 打开验收弹窗
     */
    openAcceptDialog(row) {
      this.acceptForm = {
        renovationId: row.renovationId || '',
    renovationApprover: '', // 默认空
    status: '',               // 默认空，后端会更新
    acceptanceDesc: ''        // 默认空
      }
      this.acceptDialogVisible = true
    },

    /**
     * 提交验收
     */
    submitAccept() {
       this.$refs.acceptFormRef.validate((isValid) => {
    if (!isValid) return;

       // 提交数据
const submitData = {
  renovationId: this.acceptForm.renovationId,
  renovationAcceptance: this.acceptForm.renovationAcceptance, // 验收人
  status: this.acceptForm.status,               // 文字，后端转换
  acceptanceDesc: this.acceptForm.acceptanceDesc
};

console.log('提交验收前的数据:', submitData);
    if (!submitData.renovationId) {
      this.$message.error('装修ID不能为空');
      return;
    }
  

    this.$axios.post("http://localhost:8080/renovation/approve", submitData)
      .then(res => {
        if (res.data.code === 200) {
          this.$message.success('验收提交成功！');
          this.acceptDialogVisible = false;
          this.fetchTable(); // 刷新表格
        } else {
          this.$message.error(res.data.msg || '验收提交失败');
        }
      })
      .catch(err => {
        this.$message.error('网络异常，提交失败');
      });
  });
},

    /**
     * 打开详情弹窗
     */
    openDetailDialog(row) {
      // 调用详情接口获取完整数据（也可直接用表格行数据，建议用接口确保数据最新）
      this.$axios.get(`http://localhost:8080/renovation/detail/${row.renovationId}`)
        .then(res => {
          if (res.data.code === 200 && res.data.data) {
            this.detailForm = res.data.data
            this.detailDialogVisible = true
          } else {
            this.$message.error(res.data.msg || '获取详情失败')
          }
        })
        .catch(err => {
          this.handleError(err, '获取详情失败')
        })
    },

    /**
     * 打开新增弹窗
     */
   openAddDialog() {
      this.isEdit = false;
      this.addEditForm = {
        communityName: '',
        buildingName: '',
        unitName: '',
        roomName: '',
        constructionCompany: '',
        renovationApplyPerson: '',
        renovationApplyPhone: '',
        renovationDeposit: 0,
        renovationContent: ''
      };
      this.addEditDialogVisible = true;
    },

    /**
     * 打开编辑弹窗
     */openEditDialog(row) {
  this.isEdit = true;
  this.$axios.get(`http://localhost:8080/renovation/detail/${row.renovationId}`)
    .then(res => {
       console.log('从后端返回的数据:', res.data.data);
      if (res.data.code === 200 && res.data.data) {
        const { renovationId, constructionCompany, constructionNumber, constructionStartTime, constructionEndTime, renovationContent, renovationDeposit, renovationDesc } = res.data.data;
         console.log('提取后的字段:', { renovationId, constructionCompany, constructionNumber, constructionStartTime, constructionEndTime, renovationContent, renovationDeposit, renovationDesc });

        this.addEditForm = {
          renovationId,
          constructionCompany: constructionCompany || '',
          constructionNumber: constructionNumber || '',
          constructionStartTime: constructionStartTime || '',
          constructionEndTime: constructionEndTime || '',
          renovationContent: renovationContent || '',
          renovationDeposit: renovationDeposit || 0,
          renovationDesc: renovationDesc || ''
        };
         console.log('editForm:', this.editForm);
        this.addEditDialogVisible = true;
      } else {
        this.$message.error(res.data.msg || '获取编辑数据失败');
      }
    })
    .catch(err => {
      this.handleError(err, '获取编辑数据失败');
    });
},
    /**
     * 提交新增/编辑
     */
    submitAddEdit() {
       const formData = this.addEditForm;

         if (this.isEdit && !formData.renovationId) {
    this.$message.error('装修ID不能为空');
    return;
  }


       this.$refs.addEditFormRef.validate((isValid) => {
    if (isValid) {
      const request = this.isEdit
        ? this.$axios.post("http://localhost:8080/renovation/update", formData)
        : this.$axios.post("http://localhost:8080/renovation/add", formData);

      request.then(res => {
        if (res.data.code === 200) {
          this.$message.success(this.isEdit ? '编辑成功！' : '新增成功！');
          this.addEditDialogVisible = false;
          this.fetchTable();
        } else {
          this.$message.error(res.data.msg || (this.isEdit ? '编辑失败' : '新增失败'));
        }
      }).catch(err => {
            this.$message.error('操作失败');
          });
        }
      })
    },

    /**
     * 打开删除确认弹窗
     */
    handleDelete(row) {
  console.log("待删除的row数据：", row); 
 this.deleteId = row.renovationId
    
      this.deleteDialogVisible = true
    },

    /**
     * 提交删除
     */
    submitDelete() {
      this.$axios.delete(`http://localhost:8080/renovation/delete/${this.deleteId}`)
      
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('删除成功！')
            this.deleteDialogVisible = false
            this.fetchTable() // 刷新表格
          } else {
            this.$message.error(res.data.msg || '删除失败')
          }
        })
        .catch(err => {
          this.handleError(err, '删除失败')
        })
    }
  }
}
</script>

<style scoped>
/* 表头样式 */
::v-deep .table-head {
  background-color: #f5f7fa !important;
  color: #1f2d3d !important;
  font-weight: 500 !important;
}

/* 弹窗底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 表格行悬停样式优化 */
::v-deep .el-table__row:hover {
  background-color: #fafafa !important;
}
</style>